import store from '@/store'
class websockeUtil {
  constructor(url, time) {
    this.isOpenSocket = false // 是否连接
    this.isPeopleClose = false
    this.url = url // 链接地址
    this.data = null //传输内容
    this.timeoutNumber = time || 5 // 心跳检测间隔，单位s
    this.heartbeatTimer = null // 心跳检测定时器
    this.reconnectTimer = null // 断线重连定时器
    this.socketTask = null // websocket实例
    this.againTime = 3 // 重连等待时间(单位秒)
  }
  // 初始化websocket连接
  initSocket() {
    this.socketTask = uni.connectSocket({
      url: this.url,
      header: {
        'content-type': 'application/json',
        'Authorization': store.state.token
      },
      success: (res) => {
        console.log(res)
      },
      fail: (rej) => {
        console.log('WebSocket 连接失败')
        console.error(rej)
      }
    })
    this.openSocket()
  }

  openSocket() {
    this.socketTask.onOpen(() => {
      console.log('WebSocket 连接成功')
      this.isOpenSocket = true
      clearInterval(this.heartbeatTimer)
      clearTimeout(this.reconnectTimer)
      // 打开心跳检测
      this.heartbeatCheck()
    })
    // 监听 WebSocket 接受到服务器的消息事件
    this.socketTask.onMessage((res) => {
      console.log('收到消息')
      uni.$emit('message', res)
    })
    
    // 监听 WebSocket 连接关闭事件
    // this.socketTask.onClose(() => {
    //   console.log('onClose');
    //   this.isOpenSocket = false
    //   //重连
    //   this.reconnect();
    // })
    // 监听 WebSocket 错误事件
    this.socketTask.onError((err) => {
      this.isOpenSocket = false
      this.isPeopleClose = false
      console.log('onError');
    })
  }

  //发送消息
  sendMsg(value, callback) {
    this.socketTask.send({
      data: JSON.stringify(value),
      success: async() => {
        console.log('消息发送成功')
        callback()
      },
      fail: async() => {
        console.log('消息发送失败')
        //重连
        this.reconnect();
      }
    })
  }

  // 开启心跳检测
  heartbeatCheck() {
    console.log('开启心跳')
    this.data = { sendType: 0}
    this.heartbeatTimer = setInterval(() => {
      this.sendMsg(this.data, () => {})
    }, this.timeoutNumber * 1000)
  }

  // 重新连接
  reconnect() {
    // 停止发送心跳
    clearTimeout(this.reconnectTimer)
    clearInterval(this.heartbeatTimer)
    // 如果不是人为关闭的话，进行重连
    if (!this.isPeopleClose) {
      this.reconnectTimer = setTimeout(() => {
        this.initSocket()
      }, this.againTime * 1000)
    }
  }

  // 关闭 WebSocket 连接
  closeSocket(reason = '关闭') {
    const _this = this
    this.socketTask && this.socketTask.close({
      reason,
      success() {
        _this.data = null
        _this.isOpenSocket = false
        _this.isPeopleClose = true
        _this.socketTask = null
        clearInterval(_this.heartbeatTimer)
        clearTimeout(_this.reconnectTimer)
        console.log('关闭 WebSocket 成功')
      },
      fail() {
        console.log('关闭 WebSocket 失败')
      }
    })
  }
}


module.exports = websockeUtil